import type { Article, ArticleContent, ArticleStyles } from "./types";
import { dayjs } from "element-plus";
import { defineStore } from "pinia";

export const useArticleStore = defineStore("article", () => {
  const articles = ref<Article[]>([]);
  const currentArticle = ref<Article | null>(null);

  const loadCurrentArticle = () => {
    const storedCurrentArticle = localStorage.getItem("currentArticle");
    if (storedCurrentArticle) {
      currentArticle.value = JSON.parse(storedCurrentArticle);
    }
  };

  const saveCurrentArticle = () => {
    localStorage.setItem(
      "currentArticle",
      JSON.stringify(currentArticle.value)
    );
  };

  const updateCurrentArticle = (articleId?: string) => {
    if (articleId) {
      const article = articles.value.find(
        (article) => article.id === articleId
      );
      article && (currentArticle.value = article);
    } else {
      currentArticle.value = null;
    }
  };

  const getCurrentArticle = computed(() => {
    return currentArticle.value;
  });

  const loadArticles = () => {
    const storedArticles = localStorage.getItem("articles");
    if (storedArticles) {
      articles.value = JSON.parse(storedArticles);
    }
  };

  const saveArticles = () => {
    localStorage.setItem("articles", JSON.stringify(articles.value));
  };

  const addArticle = (addArticle: ArticleContent) => {
    const currentTime = dayjs().format("YYYY-MM-DD HH:mm:ss");

    const article = {
      ...addArticle,
      id: generateUUid(),
      createTime: currentTime,
      updateTime: currentTime,
    };
    articles.value.unshift(article);
    return article;
  };

  const _findArticleIndex = (id: string) => {
    return articles.value.findIndex((article) => article.id === id);
  };

  const updateArticle = (id: string, updatedArticle: ArticleContent) => {
    const currentTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
    const index = _findArticleIndex(id);
    console.log(index, "idex");

    if (index !== -1) {
      console.log({ updatedArticle });

      articles.value[index] = {
        ...articles.value[index],
        ...updatedArticle,
        updateTime: currentTime,
      };
    }
  };

  const updateArticleHtmlContent = (articleId: string, htmlContent: string) => {
    // 删除到最后会剩余一个 br标签
    if (htmlContent === "<br>") {
      htmlContent = "";
    }
    const currentTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
    const index = _findArticleIndex(articleId);
    if (index !== -1) {
      articles.value[index].updateTime = currentTime;
      articles.value[index].htmlContent = htmlContent;
      articles.value[index].textContent =
        htmlContent && extractTextFromHtml(htmlContent);
      updateCurrentArticle(articleId);
    }
  };

  const updateArticleStyle = (
    articleId: string,
    styleId: string,
    style: MyPartial<ArticleStyles>
  ) => {
    const index = _findArticleIndex(articleId);
    if (index !== -1) {
      const article = articles.value[index];
      article.styles || (article.styles = {});
      article.styles[styleId] = {
        ...article.styles[styleId],
        ...style,
      };
    }
  };

  const deleteArticle = (id: string) => {
    const index = _findArticleIndex(id);
    if (index !== -1) {
      articles.value.splice(index, 1);
    }
  };

  const hasArticleTile = (title: string) => {
    return articles.value.some((article) => article.title === title);
  };

  const clearCurrentArticle = () => {
    currentArticle.value = null;
  };

  const getArticleList = computed(() => {
    return articles.value;
  });

  function removeNoExistIdFromStyles() {
    const article = articles.value.find(
      (article) => article.id === currentArticle.value?.id
    )!;
    for (const styleId in article.styles) {
      if (!article.htmlContent.includes(styleId)) {
        delete article.styles[styleId];
      }
    }
  }

  loadArticles();
  loadCurrentArticle();

  watch(articles, saveArticles, { deep: true });
  watch(currentArticle, saveCurrentArticle, { deep: true });

  return {
    addArticle,
    updateArticle,
    deleteArticle,
    hasArticleTile,
    getArticleList,
    updateCurrentArticle,
    clearCurrentArticle,
    updateArticleStyle,
    updateArticleHtmlContent,
    getCurrentArticle,
    removeNoExistIdFromStyles,
  };
});
